<?php
//地区格式化

//301URL内部跳转
function URL($url){
	if (empty($url)){
		exit("请提供URL");
	}
	header("HTTP:/1.1 301 Moved Permanently");
	$id=$_GET['id'];
	$tur=C('url')."/{$url}";
	header("Location:{$tur}");
	exit(0);
}
//301URL外站跳转
function URLS($url){
	if (empty($url)){
		exit("请提供URL");
	}
	header("HTTP:/1.1 301 Moved Permanently");
	header("Location:{$url}");
	exit(0);
}
//获取用户mds5字符串
function getUseMd5Srt($username){
	$user=M("User");
	$rows=$user->where("user_id='{$username}'")->find();
	return md5($rows['user_las_time'].$rows['user_las_ip']);
}
/**
 * 获取来源域名
 * Enter description here ...
 */
function getDomain($http=false){
	/* 来源 */
	if (!empty($_SERVER['HTTP_REFERER']) && strlen($_SERVER['HTTP_REFERER']) > 9)
	{
		$pos = strpos($_SERVER['HTTP_REFERER'], '/', 9);
		if ($pos !== false)
		{
			$domain = substr($_SERVER['HTTP_REFERER'], 0, $pos);
			$path   = substr($_SERVER['HTTP_REFERER'], $pos);

			/* 来源关键字 */
			/*if (!empty($domain) && !empty($path))
			 {
			save_searchengine_keyword($domain, $path);
			}*/
		}
		else
		{
			$domain = $path = '';
		}

	}
	else
	{
		$domain = $path = '';
	}
	if ($http==false){
		return addslashes($domain);
	}else{
		preg_match_all("/^(http:\/\/)?([^\/]+)/",$domain,$array);
		return addslashes($array[2][0]);
	}
}
function getdomains($host){
	$host = strtolower ( $host );
	if (strpos ( $host, '/' ) !== false) {
		$parse = @parse_url ( $host );
		$host = $parse ['host'];
	}
	$topleveldomaindb = array ('com', 'edu', 'gov', 'int', 'mil', 'net', 'org', 'biz', 'info', 'pro', 'name', 'museum', 'coop', 'aero', 'xxx', 'idv', 'mobi', 'cc', 'me' );
	$str = '';
	foreach ( $topleveldomaindb as $v ) {
		$str .= ($str ? '|' : '') . $v;
	}
	$matchstr="http:\/\/[^\.]+\.(?:(".$str.")|\w{2}|((".$str.")\.\w{2}))$";
	if (preg_match ( "/" . $matchstr . "/ies", $host, $matchs )) {
		$domain = $matchs ['0'];
	} else {
		$domain = $host;
	}
	return $domain;
}
/**
 * 获得IP
 * Enter description here ...
 */
function getIP(){

	static $realip = NULL;

	if ($realip !== NULL)
	{
		return $realip;
	}

	if (isset($_SERVER))
	{
		if (isset($_SERVER['HTTP_X_FORWARDED_FOR']))
		{
			$arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);

			/* 取X-Forwarded-For中第一个非unknown的有效IP字符串 */
			foreach ($arr AS $ip)
			{
				$ip = trim($ip);

				if ($ip != 'unknown')
				{
					$realip = $ip;

					break;
				}
			}
		}
		elseif (isset($_SERVER['HTTP_CLIENT_IP']))
		{
			$realip = $_SERVER['HTTP_CLIENT_IP'];
		}
		else
		{
			if (isset($_SERVER['REMOTE_ADDR']))
			{
				$realip = $_SERVER['REMOTE_ADDR'];
			}
			else
			{
				$realip = '0.0.0.0';
			}
		}
	}
	else
	{
		if (getenv('HTTP_X_FORWARDED_FOR'))
		{
			$realip = getenv('HTTP_X_FORWARDED_FOR');
		}
		elseif (getenv('HTTP_CLIENT_IP'))
		{
			$realip = getenv('HTTP_CLIENT_IP');
		}
		else
		{
			$realip = getenv('REMOTE_ADDR');
		}
	}

	preg_match("/[\d\.]{7,15}/", $realip, $onlineip);
	$realip = !empty($onlineip[0]) ? $onlineip[0] : '0.0.0.0';

	return $realip;

}
/**
 * 获取当前脚本
 * Enter description here ...
 */
function getCurrentAddress($basename=false){
	if (isset($_SERVER['PHP_SELF']))
	{
		define('PHP_SELF', $_SERVER['PHP_SELF']);
	}
	else
	{
		define('PHP_SELF', $_SERVER['SCRIPT_NAME']);
	}
	$patch=basename(PHP_SELF);
	if ($basename==false) $patch=PHP_SELF;
	return $patch;
}

//处理二维数组
function assoc_unique($arr, $key) {
	$tmp_arr = array();
	foreach($arr as $k => $v) {
		if(in_array($v[$key], $tmp_arr)) {
			unset($arr[$k]);
		} else {
			$tmp_arr[] = $v[$key];
		}
	}
	sort($arr);
	return $arr;
}
//二维数组排序列
function array_sort($arr,$keys,$type='asc'){
	$keysvalue = $new_array = array();
	foreach ($arr as $k=>$v){
		$keysvalue[$k] = $v[$keys];
	}
	if($type == 'asc'){
		asort($keysvalue);
	}else{
		arsort($keysvalue);
	}
	reset($keysvalue);
	foreach ($keysvalue as $k=>$v){
		$new_array[$k] = $arr[$k];
	}
	return $new_array;
}
//根据用户id得出用户信息
function getUserData($uid,$name=""){
	$user=M("Users");
	$rows=$user->where("user_id={$uid}")->find();
	if (empty($name)){
		return $rows;
	}else{
		
		return $rows["$name"];
	}
}
/**
 * 转移文件
 * Enter description here ...
 * @param $sourceFile 源文件，相对于/Publice/upload
 * @param $targetDir 目标目录，相对于/Publice/upload
 */
function MovePublicFile($sourceFile,$targetDir){
	$sourceFile="./Public/upload/tmp/".$sourceFile;
	$targetDir="./Public/upload/".$targetDir."";
	if (file_exists($sourceFile)){
		//原图
		$targetFile=pathinfo($sourceFile);
		$targetDirs=$targetDir."/".$targetFile["basename"];
		rename($sourceFile, $targetDirs);
	}
	$img210=preg_replace('/\/(\w+)\./i',"/thumb_210_"."\\1.",$sourceFile);
	if (file_exists($img210)){
		//中图
		$targetFile=pathinfo($img210);
		rename($img210, $targetDir."/".$targetFile["basename"]);
	}
	$img50=preg_replace('/\/(\w+)\./i',"/thumb_50_"."\\1.",$sourceFile);
	if (file_exists($img50)){
		//小图
		$targetFile=pathinfo($img50);
		rename($img50, $targetDir."/".$targetFile["basename"]);
	}
}
//curl提交数据
function curl_post($url,$post_data=array()){
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL, $url);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt($ch, CURLOPT_POST, 1);
	curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
	$output = curl_exec($ch);
	curl_close($ch);
	return $output;
}
//计算字符长度
function str_len($str)
{
	$length = strlen(preg_replace('/[\x00-\x7F]/', '', $str));
	if ($length)
	{
		return strlen($str) - $length + intval($length / 3) * 2;
	}
	else
	{
		return strlen($str);
	}
}
//检查用户是否登录
function  isLogin(){
	$cookie_name=$_COOKIE["zdh_buty_user"];
	if (!empty($cookie_name)){
		$Cache=$Cache = Cache::getInstance('Memcache');
		$rows=$Cache->get(substr($cookie_name,0,-8));
		return $rows["userid"];
	}else{
		return false;
	}
}

//检测对接key+检测用户是否登录
function check_key(){
	if (isLogin()>1){
		return isLogin();
	}
	if (empty($_POST["user_id"])){
		return 0;
	}
	$key=empty($_GET["vkey"])?$_POST["vkey"]:$_GET["vkey"];
	if (empty($key)) return false;
	if ($key==md5(C("VKEY"))){
		return intval($_POST["user_id"]);
	}else{
		return 0;
	}
}
function JSON($data,$info='',$status=1,$type='JSON'){
	if (!empty($_GET["data_type"])){
		$type=$_GET["data_type"];
	}
	$result  =  array();
	$result['status']  =  $status;
	$result['info'] =  $info;
	$result['data'] = $data;
	if (empty($_GET["callback"])){

		if(empty($type)) $type  =   C('DEFAULT_AJAX_RETURN');
		if(strtoupper($type)=='JSON') {
			header("Content-Type:text/html; charset=utf-8");
			exit(json_encode($result));
		}elseif(strtoupper($type)=='XML'){
			header("Content-Type:text/xml; charset=utf-8");
			exit(xml_encode($result,"utf-8","beauty"));
		}elseif(strtoupper($type)=='EVAL'){
			header("Content-Type:text/html; charset=utf-8");
			exit($data);
		}
	}else {
		$json=$_GET["callback"]."(".json_encode($result).")";
		header("Content-Type:text/html; charset=utf-8");
		exit($json);
	}
}
//验证来源合法性
function SessionRegValidationSource(){
	session_start();
	$key=empty($_POST["keys"])?mysql_escape_string($_GET["keys"]):mysql_escape_string($_POST["keys"]);
	$user=M("User");
	$rows=$user->where("dev_key = '{$key}'")->find();
	if (!count($rows)) exit("你所提供的开发者Key不正确");
	$my_key="http://".getDomain(true)."_".$key;
	$my_key=md5($my_key);
	$_SESSION["my_key"]=$my_key; //生成来源key
	$_SESSION["keys"]=$key;	//表中的key
}
function CheckMail($email){
	if (preg_match("/^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/",$email)){
		return true;
	}else{
		return false;
	}
}
function logs($datas){
	$str=curl_post(C("ADMIN_URL")."?m=post&a=PostAdminLog",$datas);
	if (strpos("success", $str)>2){
		return true;
	}else{
		return false;
	}
}
//检测远程文件是否存在
function remote_file_exists($url) {
	$curl = curl_init($url); // 不取回数据
	curl_setopt($curl, CURLOPT_NOBODY, true);
	curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'GET'); // 发送请求
	$result = curl_exec($curl);
	$found = false; // 如果请求没有发送失败
	if ($result !== false) {
		// 再检查http响应码是否为200
		$statusCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
		if ($statusCode == 200) {
			$found = true; } }
			curl_close($curl);
			return $found;
}
/**
 * 使用天数计算月、年
 * Enter description here ...
 */
function day_calculation($day){
	if ($day>=30 && $day<360){
		$str=$day/30;
		$str=round($str)+0;
		$str=$str."个月前";
	}elseif ($day>=365){
		$str=$day/360;
		$str=round($str)+0;
		$str=$str."年前";
	}elseif ($day>0 && $day<30) {
		$str=$day."天前";
	}else {
		$str=0;
	}
	return $str;
}
/**
 * 获取商品好评、中评、差评的记录数
 * @param unknown_type $id
 * @param unknown_type $runk
 */
function getCommentRank($id,$runk=0,$isWhere=false){
	$id=intval($id);
	$comment=M("Comment");
	$where=array(
			"id_value"=>$id,
			"status"=>1
			);
	switch ($runk){
		case 1:
			//差评
			$where="comment_rank <= 1 and (status=1 and id_value=$id)";
			break;
		case 2:
			//中评
			$where="comment_rank>=2 and comment_rank<=3 and (status=1 and id_value=$id)";
			break;
		case 3:
			$where="comment_rank>=4 and comment_rank<=5 and (status=1 and id_value=$id)";
			break;	
		default:
			//全部评价
			$where=array(
				"status"=>1,
				"id_value"=>$id
			);
			
	}
	if(!$isWhere){
		$rows=$comment->where($where)->count();
		
	}else{
		return $where;
	}
	return $rows;
	
}

/**
 * 获取评价回复列表
 * @param unknown_type $id			评价ID
 * @param unknown_type $number		显示数量，默认5条
 * @param unknown_type $isCount		是否统计结果数量
 */
function getCommentReplyList($id,$number=5,$isCount=false){
	if (empty($id)) JSON(0,"没有评价ID",0);
	$comment_reply=D("CommentReply");
	$where=array(
			"comment_id"=>intval($id),
			"status"=>1
	);
	if ($isCount){
		$rows=$comment_reply->where($where)->order("add_time desc")->count();
	}else{
		$rows=$comment_reply->where($where)->order("add_time desc")->limit(intval($number))->select();
		
	}
	return $rows;



}
//根据 parent_id返回父级信息
function getIdParentData($parent_id,$field=""){
	
	$comment_reply=D("CommentReply");
	
	$where=array(
			"reply_id"=>$parent_id,
			"status"=>1
	
	);
	//查找父级数据
	$rows=$comment_reply->where($where)->find();
	if (empty($field)){
		return $rows;
	}else{
		return $rows[$field];
	}
}

function dotran($str) {
	 $str=strtr(stripslashes($str), array(
                "\r"   => '', "\n"   => '', "\t"   => '', "\b"   => '',
                "\x00" => '', "\x01" => '', "\x02" => '', "\x03" => '',
                "\x04" => '', "\x05" => '', "\x06" => '', "\x07" => '',
                "\x08" => '', "\x0b" => '', "\x0c" => '', "\x0e" => '',
                "\x0f" => '', "\x10" => '', "\x11" => '', "\x12" => '',
                "\x13" => '', "\x14" => '', "\x15" => '', "\x16" => '',
                "\x17" => '', "\x18" => '', "\x19" => '', "\x1a" => '',
                "\x1b" => '', "\x1c" => '', "\x1d" => '', "\x1e" => '',
                "\x1f" => ''
        ));
	return $str;
	 
}

//获取资询回复列表(单条)
function getQuestionReply($id,$status=1){
	$question=D("Question");
	$where=array(
			"parent_id"=>$id,
			"status"=>$status
			);
	$rows=$question->where($where)->find();
	return  $rows;
	
}
//根据评价ID，返回评价信息
function getIdComment($id,$field="",$status=1){
	
	$comment=M("Comment");
	$where=array(
			"comment_id"=>intval($id),
			"status"=>$status,
			);
	$rows=$comment->where($where)->find();
	if (empty($field)){
		return $rows;
	}else{
		return $rows[$field];
	}
}

